﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using ComicIsland.App.CIHelper;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.ComicDatabase;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.ReadComicImage
{
    public partial class ReadPagePanorama : PhoneApplicationPage
    {
        private int comicId = 0, comicPartId = 0;
        private string comicTitle = string.Empty, comicPartTitle = string.Empty;
        //
        private ObservableCollection<DbImage> dbImages = new ObservableCollection<DbImage>();
        private DbImage currentDbImageItem = null;
        private int currentDbImageIndex = 0;
        //
        private DispatcherTimer timerLocalCacheImage = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(500) };
        private bool IsRunningTimerLocalCacheImage = false;

        public ReadPagePanorama()
        {
            InitializeComponent();
            //
            this.ManipulationDelta += ReadPagePanorama_ManipulationDelta;
            this.ManipulationStarted += ReadPagePanorama_ManipulationStarted;
            this.ManipulationCompleted += ReadPagePanorama_ManipulationCompleted;
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string tmpComicId, tmpComicPartId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicPartId", out tmpComicPartId);
            int.TryParse(tmpComicPartId, out comicPartId);
            if (comicPartId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicTitle", out comicTitle);

            //
            this.timerLocalCacheImage.Tick += timerLocalCacheImage_Tick;
            this.timerLocalCacheImage.Start();
            //
            base.OnNavigatedTo(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.popupContent.IsOpen)
            {
                this.popupContent.IsOpen = false;
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        void timerLocalCacheImage_Tick(object sender, EventArgs e)
        {
            if (this.IsRunningTimerLocalCacheImage)
            {
                return;
            }
            LoadComicChapterImage();
            Init.Begin();
        }

        #region ******************************页面事件******************************


        void ReadPagePanorama_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            e.Handled = true;
            FrameworkElement originalSource = e.OriginalSource as FrameworkElement;
            Point point = e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
            // ((position.Y < 200 || position.Y > 600) && position.X < 240)
            if (this.currentDbImageIndex <= 0
                && (e.TotalManipulation.Translation.X > 0
                || (e.TotalManipulation.Translation.X == 0 && point.X < 240 && (point.Y < 200 || point.Y > 600))))
            {
                MessageToastManager.Show("已经是本章节的首页了！");
                return;
            }
            if (this.currentDbImageIndex >= this.dbImages.Count - 1
                & (e.TotalManipulation.Translation.X < 0
                || (e.TotalManipulation.Translation.X == 0 && point.X > 240 && (point.Y < 200 || point.Y > 600))))
            {
                MessageToastManager.Show("已经是本章节的最后一页了！");
                return;
            }
            this.OnTouchFlick(originalSource, point, e.TotalManipulation.Translation.X);
        }

        void ReadPagePanorama_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            e.Handled = true;
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
        }

        void ReadPagePanorama_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Handled = true;
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);

            //this.OnTouchDrag(e.DeltaManipulation.Translation.X);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="touchTarget"></param>
        /// <param name="position"></param>
        /// <param name="xTotal">滑动值，如果没有进行左右滑动则为0</param>
        private void OnTouchFlick(FrameworkElement touchTarget, Point position, double xTotal)
        {
            //手势滑动才翻页
            if (xTotal < 0)
            {
                LogHelper.LogInfo("Next");
                SetImageNextOrPrevious(NextOrPrevious.Next);
                return;
            }
            if (xTotal > 0)
            {
                LogHelper.LogInfo("Previous");
                SetImageNextOrPrevious(NextOrPrevious.Previous);
                return;
            }

            //中间区域则弹出菜单
            if (position.Y > 200 && position.Y < 600 && position.X < 340 && position.X > 140)
            {
                LogHelper.LogInfo("ApplicationBar");
                this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;
                this.popupProgress.IsOpen = !this.popupProgress.IsOpen;
                return;
            }

            //单击换页
            //if ((position.Y > 200 && position.Y < 600 && position.X < 140) || ((position.Y < 200 || position.Y > 600) && position.X < 240))
            //{
            //    LogHelper.LogInfo("Previous");
            //    SetImageNextOrPrevious(NextOrPrevious.Previous);
            //    return;
            //}
            //if ((position.Y > 200 && position.Y < 600 && position.X > 340) || (position.Y < 200 || position.Y > 600) && position.X > 240)
            //{
            //    LogHelper.LogInfo("Next");
            //    SetImageNextOrPrevious(NextOrPrevious.Next);
            //    return;
            //}
        }

        public enum NextOrPrevious
        {
            Next,
            Previous
        }

        private void SetImageNextOrPrevious(NextOrPrevious nextOrPrevious)
        {
            if (nextOrPrevious == NextOrPrevious.Previous)
            {
                this.Previous.Stop();
                //
                if (this.currentDbImageIndex > this.dbImages.Count - 1)
                {
                    this.currentDbImageIndex = this.dbImages.Count;
                    this.currentDbImageIndex--;//多减一个
                }
                this.currentDbImageIndex--;
                if (this.currentDbImageIndex < 0)
                {
                    //重新初始化
                    Init.Stop();
                    //MessageBox.Show("First");                    
                    this.middleImage.Source = this.BindImage(this.dbImages[0]);
                    //this.BindImage(this.dbImages[0], this.middleImage);
                    //                    
                    this.rightImage.Source = this.BindImage(this.dbImages[1]);
                    //this.BindImage(this.dbImages[1], this.rightImage);
                    Init.Begin();
                    return;
                }
                this.rightImage.Source = this.middleImage.Source;
                this.middleImage.Source = this.leftImage.Source;
                this.leftImage.Source = this.BindImage(this.dbImages[this.currentDbImageIndex]);
                //this.BindImage(this.dbImages[this.currentDbImageIndex], this.leftImage);
                //
                this.Previous.Begin();
            }
            if (nextOrPrevious == NextOrPrevious.Next)
            {
                this.Next.Stop();
                //
                if (this.currentDbImageIndex < 0)
                    this.currentDbImageIndex = 0;
                this.currentDbImageIndex++;
                if (this.currentDbImageIndex > this.dbImages.Count - 1)
                {
                    MessageToastManager.Show("已经是最后一页啦！");
                    return;
                }
                this.leftImage.Source = this.middleImage.Source;
                this.middleImage.Source = this.rightImage.Source;
                this.rightImage.Source = this.BindImage(this.dbImages[this.currentDbImageIndex]);
                //this.BindImage(this.dbImages[this.currentDbImageIndex], this.rightImage);
                //
                Next.Begin();
            }
            this.sliderPopupProgress.Value = this.currentDbImageIndex + 1;
        }
        string GetFilePath(DbImage dbImage)
        {
            return string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dbImage.ComicId, "_", dbImage.PartId, "_", MD5.GetMd5String(dbImage.ImageUrl));
        }
        #endregion ******************************页面事件******************************



        #region ******************************加载数据******************************

        void LoadComicChapterImage()
        {
            if (this.IsRunningTimerLocalCacheImage)
            {
                return;
            }

            this.dbImages = App.comicDbHelper.ImageGetByComicIdAndChapterId(this.comicId, this.comicPartId);
            if (this.dbImages != null && this.dbImages.Count > 0)
            {
                this.timerLocalCacheImage.Stop();
                this.IsRunningTimerLocalCacheImage = false;
                //有本地缓存图片
                this.currentDbImageIndex = 0;
                this.middleImage.Source = this.BindImage(this.dbImages[0]);
                this.rightImage.Source = this.BindImage(this.dbImages[1]);
                //this.BindImage(this.dbImages[0], this.middleImage);
                //this.BindImage(this.dbImages[1], this.rightImage);
                //                
                this.sliderPopupProgress.Maximum = this.dbImages.Count;
                this.sliderPopupProgress.Value = 1;
                //
                System.Threading.Tasks.Task.Run(() =>
                {
                    BackgroundTransferHelper btHelper = new BackgroundTransferHelper();
                    btHelper.InitDownloadQueue(this.comicId);
                    this.IsRunningTimerLocalCacheImage = false;
                });
                return;
            }

            DbComic dbComic = App.comicDbHelper.ComicGetOne(this.comicId);
            if (dbComic == null)
            {
                //加载漫画信息
                this.IsRunningTimerLocalCacheImage = true;
                this.LoadComicSummaryCache(this.comicId);
            }
            else
            {
                //
                DbChapter dbChapter = App.comicDbHelper.ChapterGetOne(this.comicId, this.comicPartId);
                if (dbChapter == null)
                {
                    //加载漫画章节信息
                    this.IsRunningTimerLocalCacheImage = true;
                    this.LoadComicChapterCache(this.comicId);
                }
                else
                {
                    //
                    this.dbImages = App.comicDbHelper.ImageGetByComicIdAndChapterId(this.comicId, this.comicPartId);
                    if (!(this.dbImages != null && this.dbImages.Count > 0))
                    {
                        //加载漫画章节中的图片信息
                        this.IsRunningTimerLocalCacheImage = true;
                        this.LoadComicChapterImageChache(this.comicId, this.comicPartId);
                    }
                    else
                    {
                        this.timerLocalCacheImage.Stop();
                        this.IsRunningTimerLocalCacheImage = false;
                        //加载缓存中的图片
                        this.currentDbImageIndex = 0;
                        this.middleImage.Source = this.BindImage(this.dbImages[0]);
                        this.rightImage.Source = this.BindImage(this.dbImages[1]);
                        //this.BindImage(this.dbImages[0], this.middleImage);
                        //this.BindImage(this.dbImages[1], this.rightImage);
                        //
                        this.sliderPopupProgress.Maximum = this.dbImages.Count;
                        this.sliderPopupProgress.Value = 1;
                    }
                }
            }
            //
            var comic = App.comicDbHelper.ComicGetOne(this.comicId);
            if (comic != null)
            {
                this.comicTitle = comic.ComicTitle;
                this.txtPopupProgressTitle.Text = string.Concat(comic.ComicTitle, "-", this.comicTitle);
            }
        }

        private BitmapImage BindImage(DbImage dbImage)
        {
            string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dbImage.ComicId, "_", dbImage.PartId, "_", MD5.GetMd5String(dbImage.ImageUrl));
            BitmapImage bitmapImage = new BitmapImage();
            try
            {

                if (!IsolatedStorageHelper.Instance.FileExists(filePath))
                {
                    this.gridLoading.Visibility = System.Windows.Visibility.Visible;
                    LogHelper.LogInfo(string.Concat("加载网络图片！", dbImage.ImageUrl));
                    bitmapImage.UriSource = new Uri(dbImage.ImageUrl, UriKind.Absolute);//取网络图片                        
                    bitmapImage.ImageOpened += delegate(object sender, RoutedEventArgs e)
                    {
                        LogHelper.LogInfo("bitmapImage_ImageOpened");
                        this.gridLoading.Visibility = System.Windows.Visibility.Collapsed;
                        this.ImageOpenedAndSaveImage(bitmapImage, filePath);
                    };
                }
                else
                {
                    try
                    {
                        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream isoStream = store.OpenFile(filePath, FileMode.Open))
                            {
                                Stream fileStream = new MemoryStream();
                                isoStream.CopyTo(fileStream);
                                isoStream.Close();
                                isoStream.Dispose();
                                store.Dispose();
                                bitmapImage.SetSource(fileStream);
                                this.gridLoading.Visibility = System.Windows.Visibility.Collapsed;
                            }
                        }
                    }
                    catch { }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }

            return bitmapImage;
        }

        /// <summary>
        /// BitmapImage转换为文件存储
        /// </summary>
        /// <param name="bitmapImage"></param>
        /// <param name="filePath"></param>
        void ImageOpenedAndSaveImage(BitmapImage bitmapImage, string filePath)
        {
            try
            {
                var writeableBitmap = new WriteableBitmap(bitmapImage);
                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                using (IsolatedStorageFileStream fileStream = isolatedStorageFile.OpenFile(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writeableBitmap.SaveJpeg(fileStream, (int)bitmapImage.PixelWidth, (int)bitmapImage.PixelHeight, 0, 100);
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
            catch { }
            finally
            { }
        }

        #endregion ******************************加载数据******************************


        #region ******************************菜单项******************************
        #region 显示目录
        /// <summary>
        /// 显示目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarComicContents_Click(object sender, EventArgs e)
        {
            this.ApplicationBar.IsVisible = false;
            this.popupProgress.IsOpen = false;
            this.txtComicTitle.Text = this.comicTitle;
            this.txtPopupProgressTitle.Text = string.Concat(this.comicTitle, this.comicPartTitle);
            LoadComicChapter(this.comicId);
            this.popupContent.Visibility = System.Windows.Visibility.Collapsed;
            this.popupContent.IsOpen = true;
            this.popupContent.Visibility = System.Windows.Visibility.Visible;
        }
        public void LoadComicChapter(int comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", comicId.ToString(), "&", KEYS.REQUEST_QUERY_PLATFORM);
            //
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.llsContent.ItemsSource = rootCharacterString.Info.BookPartList;
                }
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            this.llsContent.ItemsSource = rootCharacterString.Info.BookPartList;
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {

                    }
                });
            }, webTask);
        }

        private void btnDownloadedChapter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Button).DataContext as JsonComicChapterInfoBookPartList;
            if (item == null)
            {
                return;
            }

            this.popupContent.IsOpen = false;
            if (this.comicPartId == item.PartId)
            {
                return;//选择仍然是当前阅读章节
            }
            this.comicPartId = item.PartId;
            this.comicPartTitle = item.Name;
            LoadComicChapterImage();
        }

        private void imageClosePopup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.popupContent.IsOpen = false;
        }
        #endregion 显示目录

        #region 进度跳转
        private void sliderPopupProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.txtCurrentSliderPopupProgress.Text = ((int)e.NewValue).ToString();
            });
        }

        private void sliderPopupProgress_LostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e)
        {
            int newValue = (int)(e.OriginalSource as Slider).Value - 1;

            if (this.currentDbImageIndex == newValue)
            {
                return;
            }

            if (this.currentDbImageIndex > newValue)
            {
                this.currentDbImageIndex = newValue;
                LogHelper.LogInfo("阅读上一话," + this.currentDbImageIndex);
                //阅读上一话
                if (currentDbImageIndex > 0)
                {
                    this.leftImage.Source = BindImage(this.dbImages[this.currentDbImageIndex - 1]);
                }
                this.middleImage.Source = BindImage(this.dbImages[this.currentDbImageIndex]);
                this.rightImage.Source = BindImage(this.dbImages[this.currentDbImageIndex + 1]);
            }
            else if (this.currentDbImageIndex < newValue)
            {
                this.currentDbImageIndex = newValue;
                LogHelper.LogInfo("阅读下一话," + this.currentDbImageIndex);
                //阅读下一话
                if (currentDbImageIndex < this.dbImages.Count - 1)
                {
                    this.rightImage.Source = BindImage(this.dbImages[this.currentDbImageIndex + 1]);

                }
                this.leftImage.Source = BindImage(this.dbImages[this.currentDbImageIndex - 1]);
                this.middleImage.Source = BindImage(this.dbImages[this.currentDbImageIndex]);

            }

        }
        #endregion 进度跳转

        #region 亮度调节
        private void appBarBrightness_Click(object sender, EventArgs e)
        {
            //this.popupBrightness.IsOpen = !this.popupBrightness.IsOpen;
            //this.popupProgress.IsOpen = false;
            //this.popupContent.IsOpen = false;
        }

        private void sliderpopupBrightness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            this.Opacity = e.NewValue;
        }

        private void sliderpopupBrightness_LostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e)
        {
            //this.Opacity = (e.OriginalSource as Slider).Value;
        }
        #endregion 亮度调节

        /// <summary>
        /// 固定到桌面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PinShellToDesk(object sender, EventArgs e)
        {
            try
            {
                LocalUserBookStoreAlbumHelper helper = new LocalUserBookStoreAlbumHelper();
                var item = helper.GetOneComicFromLocalUserBookStoreAlbum(this.comicId);
                if (item == null)
                {
                    MessageToastManager.Show("操作失败！", MessageToastLevel.Error);
                    return;
                }
                string navigationUrl = string.Format("/Views/{0}.xaml?comicId={1}&IsShellTile=1", ComicIslandPage.ComicSummaryPage.ToString(), this.comicId);
                ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile p) => p.NavigationUri.ToString().Equals(navigationUrl));
                if (shellTile != null)
                {
                    MessageToastManager.Show("桌面已经有了这本漫画哦！");
                    return;
                }
                StandardTileData standardTileData = new StandardTileData();
                standardTileData.Title = this.comicTitle;
                standardTileData.BackgroundImage = (new Uri(item.Coverurl, UriKind.Absolute));
                //standardTileData.BackBackgroundImage = (new Uri(this.comicCoverUrl, UriKind.Absolute));
                //standardTileData.BackTitle = this.comicTitle;
                //standardTileData.BackContent = this.comicTitle;
                ShellTile.Create(new Uri(navigationUrl, UriKind.Relative), standardTileData);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 显示帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FastHelp_Click(object sender, EventArgs e)
        {

        }
        #endregion  ******************************菜单项******************************



        private void leftImage_Loaded(object sender, RoutedEventArgs e)
        {
            LogHelper.LogInfo("leftImage_Loaded", this.GetType(), MethodBase.GetCurrentMethod());
        }

        private void middleImage_Loaded(object sender, RoutedEventArgs e)
        {
            LogHelper.LogInfo("middleImage_Loaded", this.GetType(), MethodBase.GetCurrentMethod());
        }

        private void rightImage_Loaded(object sender, RoutedEventArgs e)
        {
            LogHelper.LogInfo("rightImage_Loaded", this.GetType(), MethodBase.GetCurrentMethod());
        }


        #region ******************************图片缩放******************************
        private const double doubleTapScale = 2;
        private bool isDouble = false;

        private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
        {
            Image currentImage = e.OriginalSource as Image;
            if (currentImage == null)
                return;

            LogHelper.LogInfo(currentImage.Name);
            //if (this.rightImage.Name.Equals(currentImage.Name))
            //{
            //    //ImageSF(this.rightImage, this.transformRightImage, this.rightImageSFX, this.rightImageSFY, this.rightImageSF);
            //}
            //else if (this.middleImage.Name.Equals(currentImage.Name))
            //{
            //    ImageSF(this.rightImage, this.transformRightImage, this.middleImageSFSX, this.middleImageSFSY, this.middleImageSFS,this.middleImageSFTX,this.middleImageSFTY,this.middleImageSFT);
            //}



        }

        private void ImageSF(Image imageControl, CompositeTransform transform,
            DoubleAnimation daSX, DoubleAnimation daSY, Storyboard storyboradS,
            DoubleAnimation daTX, DoubleAnimation daTY, Storyboard storyboradT)
        {
            if (transform.ScaleX < doubleTapScale)
            {
                double s = doubleTapScale;
                daSX.To = s;
                daSY.To = s;
                storyboradS.Begin();
                transform.ScaleY = s;
                transform.ScaleX = s;
                isDouble = true;
            }
            else
            {
                double s = 1f;
                daSX.To = s;
                daSY.To = s;
                storyboradS.Begin();
                transform.ScaleY = s;
                transform.ScaleX = s;
                isDouble = false;
                this.Reset(imageControl, transform, daSX, daSY, storyboradS, daTX, daTY, storyboradT);
            }
        }

        private void Reset(Image imageControl, CompositeTransform transform, 
            DoubleAnimation daSX, DoubleAnimation daSY, Storyboard storyboradS,
            DoubleAnimation daTX, DoubleAnimation daTY, Storyboard storyboradT)
        {
            if (transform.ScaleX < 1)
            {
                daSX.To = 1;
                daSY.To = 1;
                storyboradS.Begin();
                transform.ScaleY = transform.ScaleX = 1f;
            }
            else if (transform.ScaleX > 3)
            {
                daSX.To = 3;
                daSY.To = 3;
                storyboradS.Begin();
                transform.ScaleY = transform.ScaleX = 3f;
            }
            double tsx = (transform.ScaleX - 1) * imageControl.ActualWidth / 2;
            double tsy = (transform.ScaleY - 1) * imageControl.ActualHeight / 2;
            daTX.To = transform.TranslateX;
            double x = transform.TranslateX - tsx;
            if (x > 0)
            {
                daTX.To = tsx;
            }
            double x2 = transform.TranslateX + tsx;
            if (x2 < 0)
            {
                daTX.To = -tsx;
            }
            daTY.To = transform.TranslateY;
            double y = transform.TranslateY - tsy;
            if (y > 0)
            {
                daTY.To = tsy;
            }
            double y2 = transform.TranslateY + tsy;
            if (y2 < 0)
            {
                daTY.To = -tsy;
            }
            if (x > 0 || x2 < 0 || y > 0 || y2 < 0)
            {
                storyboradT.Begin();
                transform.TranslateX = tsx;
                transform.TranslateY = tsy;
            }
        }
        #endregion ******************************图片缩放******************************

















        #region ******************************阅读漫画的数据处理******************************


        void LoadComicSummaryCache(int comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicsdetail_v2?bigbookid=", comicId.ToString(), "&", KEYS.REQUEST_QUERY_PLATFORM);

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    //加入缓存下载队列
                    var items = rootCharacterString.Info.Comicsdetail;
                    if (items != null && items.Count > 0)
                    {
                        DownloadQueueInsertComic(items);
                    }
                }
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Comicsdetail;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                //加入缓存下载队列
                                DownloadQueueInsertComic(items);
                            }
                        }

                        #endregion 获取结果处理

                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                    }
                });
            }, webTask);
        }

        void DownloadQueueInsertComic(ObservableCollection<JsonComicDetailComicsdetail> items)
        {
            JsonComicDetailComicsdetail item = (from p in items select p).FirstOrDefault<JsonComicDetailComicsdetail>();
            if (item == null)
                return;

            DbComic dbComic = new DbComic();
            dbComic.ComicId = item.BigbookId;
            dbComic.ComicTitle = item.BigbookName;
            dbComic.CoverUrl = item.Coverurl;
            dbComic.DownloadStatus = DownloadComicChapterStatus.Pending.ToString();
            App.comicDbHelper.ComicInsert(dbComic);
            //
            //加载漫画章节信息
            this.LoadComicChapterCache(this.comicId);
        }

        void LoadComicChapterCache(int comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", comicId.ToString());

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0)
                {
                    this.DownloadQueueInsertComicChapter(rootCharacterString.Info.BookPartList);
                }
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region ********************获取结果处理********************
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            this.DownloadQueueInsertComicChapter(rootCharacterString.Info.BookPartList);
                        }
                        #endregion ********************获取结果处理********************
                    });
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }, webTask);
        }

        void DownloadQueueInsertComicChapter(ObservableCollection<JsonComicChapterInfoBookPartList> items)
        {
            if (!(items != null && items.Count > 0))
            {
                //未获取到章节信息
                return;
            }

            JsonComicChapterInfoBookPartList item = (from p in items where p.PartId == this.comicPartId select p).FirstOrDefault<JsonComicChapterInfoBookPartList>();
            if (item == null)
                return;
            DbChapter dbChapter = new DbChapter()
            {
                ComicId = this.comicId,
                PartId = item.PartId,
                Name = item.Name,
                Partsize = item.Partsize,
                Partnumber = item.Partnumber,
                Totalpage = item.Totalpage,
                Msourceparturl = item.Msourceparturl,
                Sourceparturl = item.Sourceparturl,
                DownloadStatus = DownloadComicChapterStatus.Pending.ToString(),
                ComicIdAndPartId = string.Concat(this.comicId, "#", item.PartId)
            };
            App.comicDbHelper.ChapterInsert(this.comicId, new List<DbChapter>() { dbChapter });
            //
            //加载漫画章节中的图片信息
            this.comicPartId = dbChapter.PartId;
            this.comicPartTitle = dbChapter.Name;
            this.LoadComicChapterImageChache(this.comicId, this.comicPartId);
        }

        void LoadComicChapterImageChache(int comicId, int comicPartId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&partVersion=3", comicId, comicPartId),
                "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(cacheHelper.LocalCacheData);
                if (rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info))
                {
                    var saveDbImages = new ObservableCollection<DbImage>();
                    var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                    if (itemsource != null && itemsource.Count > 0)
                    {
                        foreach (JsonComicContentInfo jcci in itemsource)
                        {
                            saveDbImages.Add(new DbImage()
                            {
                                ComicId = comicId,
                                PartId = comicPartId,
                                ImageUrl = jcci.Imgurl,
                                Referer = jcci.Referer,
                                ComicIdAndPartId = string.Concat(comicId, "#", comicPartId),
                                DownloadStatus = DownloadComicChapterStatus.Pending.ToString()
                            });
                        }
                        //
                        DownloadQueueInsertComicChapterImage(saveDbImages);
                    }
                }
                return;
            }

            //
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        #region **********获取结果处理**********
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //

                        var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                        if (rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info))
                        {
                            var saveDbImages = new ObservableCollection<DbImage>();
                            var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                            if (itemsource != null && itemsource.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                foreach (JsonComicContentInfo jcci in itemsource)
                                {
                                    saveDbImages.Add(new DbImage()
                                    {
                                        ComicId = comicId,
                                        PartId = comicPartId,
                                        ImageUrl = jcci.Imgurl,
                                        Referer = jcci.Referer,
                                        ComicIdAndPartId = string.Concat(comicId, "#", comicPartId),
                                        DownloadStatus = DownloadComicChapterStatus.Pending.ToString()
                                    });
                                }
                                //
                                DownloadQueueInsertComicChapterImage(saveDbImages);
                            }
                        }
                        #endregion **********获取结果处理**********
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }

        void DownloadQueueInsertComicChapterImage(ObservableCollection<DbImage> saveDbImages)
        {
            //漫画的章节中的图片地址列表
            if (saveDbImages != null && saveDbImages.Count > 0)
            {
                App.comicDbHelper.ImageInsertOrUpdate(saveDbImages);
                //加入下载队列
                System.Threading.Tasks.Task.Run(() =>
                {
                    BackgroundTransferHelper btHelper = new BackgroundTransferHelper();
                    btHelper.InitDownloadQueue(comicId);
                    this.IsRunningTimerLocalCacheImage = false;
                });
            }
        }
        #endregion ******************************阅读漫画的数据处理******************************






























        #region tmp
        //private void BindImage(DbImage dbImage, Image imageControl)
        //{            
        //    try
        //    {
        //        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
        //        {
        //            string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dbImage.ComicId, "_", dbImage.PartId, "_", MD5.GetMd5String(dbImage.ImageUrl));            
        //            if (IsolatedStorageHelper.Instance.FileExists(filePath))
        //            {
        //                using (IsolatedStorageFileStream isoStream = store.OpenFile(filePath, FileMode.Open))
        //                {
        //                    Stream fileStream = new MemoryStream();
        //                    isoStream.CopyTo(fileStream);

        //                    isoStream.Close();
        //                    isoStream.Dispose();
        //                    store.Dispose();

        //                    BitmapImage bitmapImage = new BitmapImage();
        //                    bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;// (BitmapCreateOptions)16;
        //                    bitmapImage.SetSource(fileStream);
        //                    imageControl.Source = (bitmapImage);

        //                    this.sp.Visibility = System.Windows.Visibility.Collapsed;
        //                }
        //            }
        //            else
        //            {
        //                AsyncCacheImageTask aciTask = new AsyncCacheImageTask(dbImage);
        //                aciTask.OnLoadProcessEvent += aciTask_OnLoadProcessEvent;
        //                aciTask.OnLoadErrorEvent += aciTask_OnLoadErrorEvent;
        //                aciTask.OnLoadCompleteEvent += delegate(AsyncCacheImageTask sender, CacheLoadCompleteEventArgs args)
        //                {
        //                    base.Dispatcher.BeginInvoke(() =>
        //                    {
        //                        try
        //                        {
        //                            using (IsolatedStorageFileStream isoStream = store.OpenFile(args.FilePath, FileMode.Open))
        //                            {
        //                                Stream fileStream = new MemoryStream();
        //                                isoStream.CopyTo(fileStream);

        //                                isoStream.Close();
        //                                isoStream.Dispose();
        //                                store.Dispose();

        //                                BitmapImage bitmapImage = new BitmapImage();
        //                                bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;// (BitmapCreateOptions)16;
        //                                bitmapImage.SetSource(fileStream);
        //                                imageControl.Source = (bitmapImage);

        //                                this.sp.Visibility = System.Windows.Visibility.Collapsed;
        //                            }
        //                        }
        //                        catch (Exception err)
        //                        {
        //                            MessageToastManager.Show(err.Message, MessageToastLevel.Error);
        //                        }
        //                    });
        //                };
        //                aciTask.Start();
        //            }
        //        }
        //    }
        //    catch (Exception err)
        //    {
        //        LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        //    }
        //}

        //void aciTask_OnLoadErrorEvent(AsyncCacheImageTask sender, CacheLoadErrorEventArgs args)
        //{
        //    base.Dispatcher.BeginInvoke(() =>
        //    {
        //        MessageToastManager.Show("网络环境不稳定,请重新加载...", MessageToastLevel.Error);
        //    });
        //}

        //void aciTask_OnLoadProcessEvent(AsyncCacheImageTask sender, CacheLoadProcessEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() =>
        //    {
        //        int curByteNum = (int)(args.CurByteNum * (long)100 / args.TotalByteNum);
        //        this.txtLoadingInfo.Text = (string.Concat("正在努力的装载中...", curByteNum, "%"));
        //    });
        //}
        #endregion tmp
    }
}